package site.jlopen.utils.csv;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import site.jlopen.controller.modules.DataController;
import site.jlopen.entity.data.TableStructure;

public class CsvUtil {
	private static Logger logger = LoggerFactory.getLogger(CsvUtil.class);

	public static List<TableStructure> readCSVStructure(MultipartFile file) {
		List<TableStructure> list = new ArrayList<TableStructure>();
		BufferedReader bufferedReader = null;
		InputStreamReader inputStreamReader = null;
		InputStream fileInputStream = null;
		try {
			CSVFormat format = CSVFormat.DEFAULT.withHeader();
			InputStreamReader isr = new InputStreamReader(file.getInputStream(), "UTF-8");
			CSVParser cSVParser = new CSVParser(isr, format);
			/*for (CSVRecord recordd : records) {
				Map<String, String> map = recordd.toMap();
			}*/
			List <CSVRecord> records = cSVParser.getRecords();
			List<String> heads = cSVParser.getHeaderNames();
			for (int i = 0; i < heads.size(); i++) {
				// CSVRecord csvRecord = parser.getRecords();
				// String determineType(CSVRecord csvRecord, i);
				String type = determineType(records.get(i), i);
				list.add(TableStructure.builder().columnName(heads.get(i)).columnType(type).columnRemark("")
						.build());
			}
		} catch (Exception e) {
			logger.error("csv文件解析异常", e);
		}
		/*try {
			fileInputStream = file.getInputStream();
			inputStreamReader = new InputStreamReader(fileInputStream);
			bufferedReader = new BufferedReader(inputStreamReader);
			CSVParser parser = CSVFormat.DEFAULT.parse(bufferedReader);
			List<String> heads = parser.getHeaderNames();
			for (int i = 0; i < heads.size(); i++) {
				// CSVRecord csvRecord = parser.getRecords();
				// String determineType(CSVRecord csvRecord, i);
				list.add(TableStructure.builder().columnName(heads.get(i)).columnType("string").columnRemark("")
						.build());
			}
		} catch (Exception e) {
			logger.error("csv文件解析异常", e);
		}*/
		/*for (List<String> csv : csvs) {
			List<String> csvdata = csv;
			list.add(TableStructure.builder().columnName(csvdata.get(0)).columnType(csvdata.get(1)).columnRemark(csvdata.get(2)).build());
		}*/
		return list;
	}

	/*public static void processCSVHead(CSVParser csvParser) {
		List<String> hedas = csvParser.getHeaderNames();
		for (CSVRecord csvRecord : csvParser) {
			String[] headers = csvParser.getHeaderNames();
			int[] types = new int[headers.length];
			for (int i = 0; i < headers.length; i++) {
				types[i] = determineType(csvRecord, i);
			}
			System.out.println("CSV Headers and Types: " + Arrays.toString(headers) + " - " + Arrays.toString(types));
		}
	}*/

	private static String determineType(CSVRecord csvRecord, int index) {
		String value = csvRecord.get(index);
		if (value.matches("\\d+\\.\\d+")) {
			return "float";
		} else if (value.matches("\\d+")) {
			return "int";
		}
		return "str";
	}

	public static List<List<String>> readCSV(MultipartFile file, int colNum) {
		BufferedReader bufferedReader = null;
		InputStreamReader inputStreamReader = null;
		InputStream fileInputStream = null;
		try {
			fileInputStream = file.getInputStream();
			inputStreamReader = new InputStreamReader(fileInputStream);
			bufferedReader = new BufferedReader(inputStreamReader);
			CSVParser parser = CSVFormat.DEFAULT.parse(bufferedReader);
			// 表内容集合，外层 List为行的集合，内层 List为字段集合
			List<List<String>> values = new ArrayList<>();
			int rowIndex = 0;
			// 读取文件每行内容
			for (CSVRecord record : parser.getRecords()) {
				// 跳过表头
				if (rowIndex == 0) {
					rowIndex++;
					continue;
				}
				// 判断下角标是否越界
				if (colNum > record.size()) {
					// 返回空集合
					return values;
				}
				// 每行的内容
				List<String> value = new ArrayList<>();
				for (int i = 0; i < colNum; i++) {
					value.add(record.get(i));
				}
				values.add(value);
				rowIndex++;
			}
			return values;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭流
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStreamReader != null) {
				try {
					inputStreamReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fileInputStream != null) {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}
